package com.bookbuf.android.permission.inf;

import android.app.Activity;
import android.util.Log;

import com.bookbuf.android.permission.PermMonitor;
import com.bookbuf.android.permission.PermUtil;
import com.bookbuf.android.permission.entity.MonitorActivityEntity;
import com.bookbuf.android.permission.entity.PermEntityCompat;

/**
 * Created by robert on 16/5/27.
 */
public class PermDelegateInfImpl implements PermDelegateInf<PermEntityCompat> {

	protected final String TAG = "PermDelegateInfImpl";

	public PermDelegateInfImpl () {
		Log.d (TAG, "getPermDelegateInfCompat: create permDelegateInf (<23)");
	}

	@Override
	public void register (Activity activity, OnRequestPermissionsResultCallback<PermEntityCompat> callback) {
		MonitorActivityEntity entity = new MonitorActivityEntity (activity, callback);
		PermMonitor.addOrUpdate (entity);
	}

	@Override
	public void trace (PermEntityCompat... permEntities) {
		final int id = PermMonitor.Box.put (permEntities);
		Log.d (TAG, "trace: id = " + id + " ==? " + PermMonitor.Box.filter (permEntities));
		PermMonitor.Box.print ();
	}

	@Override
	public void request (PermEntityCompat... permEntities) {
		if (permEntities != null) {
			MonitorActivityEntity entity = PermMonitor.get ();
			PermUtil.request (entity, permEntities);
		}
	}

	@Override
	public boolean check (PermEntityCompat... permEntities) {
		String[] permissions = PermUtil.permissions (permEntities);

		if (permissions != null) {
			/*挨个检查权限*/
			boolean granted = true;
			MonitorActivityEntity entity = PermMonitor.get ();
			granted &= PermUtil.check (entity, permEntities);
			/*处理回调结果*/
			OnRequestPermissionsResultCallback<PermEntityCompat> callback = (OnRequestPermissionsResultCallback<PermEntityCompat>) entity.getCallback ();
			callback.onChecked (granted, permEntities);
			return granted;
		} else {
			/*不存在需要检查的权限*/
			return false;
		}
	}

	@Override
	public void parse (int traceId, String[] strings, int[] grants) {
		PermEntityCompat[] permEntities = PermMonitor.Box.filter (traceId);
		if (permEntities == null || strings.length != permEntities.length || grants.length != permEntities.length) {
			Log.e (TAG, "parse: 请求权限 与 返回结果列表数量不匹配");
			return;
		}
		MonitorActivityEntity entity = PermMonitor.get ();
		boolean granted = PermUtil.check (entity, permEntities);

		/*处理回调结果*/
		OnRequestPermissionsResultCallback<PermEntityCompat> callback = (OnRequestPermissionsResultCallback<PermEntityCompat>) entity.getCallback ();
		if (granted) {
			callback.onGranted (permEntities);
		} else {
			callback.onDenied (permEntities);
		}
	}

	@Override
	public void untrace (int traceId) {
		if (traceId != -1) {
			PermMonitor.Box.remove (traceId);
		}
		PermMonitor.Box.print ();
	}

	@Override
	public void unregister (Activity activity, OnRequestPermissionsResultCallback<PermEntityCompat> callback) {
		PermMonitor.clear ();
	}
}
